#include "head.h"

int send_file(int socketfd, char *name){
    int fd = open(name, O_RDONLY);
    send(socketfd, &fd, sizeof(fd), 0);
    if(fd == -1){
        printf("没有客户端要求的文件\n");
        return -1;
    }
    
    //发送文件大小
    struct stat stat_t;
    fstat(fd, &stat_t);
    printf("file size: %ld\n", stat_t.st_size);
    send(socketfd, &stat_t.st_size, sizeof(off_t), MSG_WAITALL);
    
    //发送文件
    while(1){
        char buf[1024]={0};
        int ret_read = read(fd, buf, sizeof(buf));
        if(ret_read == 0){
            int flag_exit = 0;
            send(socketfd, &flag_exit, sizeof(int),MSG_NOSIGNAL);
            printf("文件传输完毕\n");
            break;
        }
        send(socketfd, &ret_read, sizeof(int), MSG_NOSIGNAL);
        send(socketfd, buf, ret_read, MSG_NOSIGNAL);
    }
    close(fd);
    return 0;
}

int recv_file(int socketfd, char *name){
    chdir("download");
    int fd = open(name, O_WRONLY|O_CREAT|O_TRUNC, 0664);
    chdir("..");
    //为要接收的文件预留空间
    off_t file_size;
    recv(socketfd, &file_size, sizeof(off_t),MSG_WAITALL);
    int ret_fruncate = ftruncate(fd, file_size);
    ERROR_CHECK(ret_fruncate, -1, "ftruncate");

    //接收文件
    while(1){
        int len;
        char buf[1024]={0};
        recv(socketfd, &len, sizeof(len), MSG_WAITALL);
        if(len == 0){
            printf("文件接收完毕\n");
            break;
        }
        recv(socketfd, buf, len, MSG_WAITALL);
        write(fd, buf, len);
    }
    close(fd);
    return 0;
}
